<!-- src/public/views/componentsWeb/FundAccountSelect.vue -->
<template>

    <!-- 只读状态显示 -->
    <span v-if="readonly">
        {{ displayValue || '-' }}
    </span>

    <!-- 可编辑状态显示 -->
    <div v-else class="input-container">
        <el-select v-model="selectedFundAccountId" :disabled="disabled" filterable remote clearable reserve-keyword
            :remote-method="remoteSearch" :loading="loading" :placeholder="placeholder" @change="handleChange">
            <el-option v-for="account in options" :key="account.id" :label="account.name" :value="account.id">
                <span style="float: left">{{ account.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px; margin-left: 20px;">余额: {{
                    formatCurrency(account.balance) }}</span>
            </el-option>
        </el-select>
    </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { DataPage } from '../../network/communicationConverter'
import { Definition } from '../../engine/common/definition'
import { Util } from '../../utils/util'
import { FundAccountFilter } from '../../engine/funds/fundAccount'
import { FundAccountInsideType } from '../../engine/common/fundDefinition'

export default {
    name: 'FundAccountSelect',
    props: {
        modelValue: {
            type: Object,
            default: null
        },
        prop: {
            type: String,
            default: 'fundAccount'
        },
        disabled: {
            type: Boolean,
            default: false
        },
        readonly: {  // 只读属性
            type: Boolean,
            default: false
        },
        placeholder: {
            type: String,
            default: '搜索账户'
        },
        rules: {
            type: Array,
            default: () => []
        },
        fundUiAction: {
            type: Object,
            required: true
        },
    },
    emits: ['update:modelValue', 'change'],
    data() {
        return {
            selectedFundAccountId: null,
            options: [],
            loading: false,
            lastQuery: '',
        }
    },
    computed: {
        displayValue() {  // 计算属性显示值
            return this.modelValue?.name || ''
        }
    },
    watch: {
        modelValue: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.selectedFundAccountId = val.id;
                } else {
                    this.selectedFundAccountId = null;
                }
            }
        }
    },
    methods: {
        formatCurrency(value) {
            return Util.getFundString(value);
        },

        async remoteSearch(query) {
            if (query === this.lastQuery) return;

            if (!this.fundUiAction) return;

            this.lastQuery = query;
            this.loading = true;

            try {
                const res = await this.fundUiAction.getFundAccountData({
                    orgId: this.$store?.state?.profile?.org?.orgId, // Assuming you have access to orgId
                    pageInfo: new DataPage(1, 0, Definition.gDefualPullDownPageSize),
                    filter: new FundAccountFilter({
                        storeId:null,
                        likeName:query,
                        accountInsideType :FundAccountInsideType.NormalAccount
                    }) // 使用name进行模糊查询
                });

                if (res.data && res.data.dataList.length > 0) {
                    this.options = res.data.dataList;
                }
            } catch (error) {
                console.error('搜索资金账户失败:', error);
                ElMessage.error('搜索资金账户失败');
            } finally {
                this.loading = false;
            }
        },

        handleChange(val) {
            const selectedAccount = this.options.find(u => u.id === val)
            if (selectedAccount) {
                this.$emit('update:modelValue', selectedAccount)
                this.$emit('change', selectedAccount)
            }
        },

        async loadDefaultOptions() {
            if (!this.fundUiAction) return;

            //console.log('fundAccountSelect loadDefaultOptions');

            let query = this.lastQuery

            this.loading = true;
            try {
                const res = await this.fundUiAction.getFundAccountData({
                    orgId: this.$store?.state?.profile?.org?.orgId, // Assuming you have access to orgId
                    pageInfo: new DataPage(1, 0, Definition.gDefualPullDownPageSize),
                    filter: new FundAccountFilter({
                        storeId:null,
                        likeName:query,
                        accountInsideType :FundAccountInsideType.NormalAccount
                    }) // 使用name进行模糊查询
                });

                if (res.data && res.data.dataList.length > 0) {
                    this.options = res.data.dataList;
                }
            } catch (error) {
                console.error('加载资金账户失败:', error);
            } finally {
                this.loading = false;
            }
        }
    },
    mounted() {
        this.loadDefaultOptions();
    }
}
</script>

<style scoped>
.input-container {
    display: block;
    width: 100%;
    text-align: left;
}
</style>